package com.ruoyi.life.service.impl;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.life.domain.*;
import com.ruoyi.life.mapper.FeApartmentCancelMapper;
import com.ruoyi.life.mapper.FeApartmentLeaseDetailMapper;
import com.ruoyi.life.mapper.FeApartmentMapper;
import com.ruoyi.life.service.IFeApartmentCancelBillService;
import com.ruoyi.life.service.IFeApartmentCancelService;
import com.ruoyi.life.service.IFeApartmentLeaseDetailService;
import com.ruoyi.life.service.manager.BuiRoomManager;
import com.ruoyi.omp.api.domain.BuiRoom;
import com.ruoyi.omp.api.domain.FeApartment;
import com.ruoyi.omp.api.enums.LeaseStateEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 公寓退租记录Service业务层处理
 *
 * @author cjie
 * @date 2022-09-20
 */
@Slf4j
@Service
public class FeApartmentCancelServiceImpl implements IFeApartmentCancelService {
    @Autowired
    private FeApartmentCancelMapper feApartmentCancelMapper;

    @Autowired
    private FeApartmentMapper feApartmentMapper;

    @Autowired
    private FeApartmentLeaseDetailMapper feApartmentLeaseDetailMapper;

    @Autowired
    private BuiRoomManager buiRoomManager;

    @Autowired
    private IFeApartmentCancelBillService apartmentCancelFeeService;

    /**
     * 查询公寓退租记录
     *
     * @param id 公寓退租记录ID
     * @return 公寓退租记录
     */
    @Override
    public FeApartmentCancel selectFeApartmentCancelById(String id) {
        return feApartmentCancelMapper.selectFeApartmentCancelById(id);
    }

    /**
     * 查询公寓退租记录列表
     *
     * @param feApartmentCancel 公寓退租记录
     * @return 公寓退租记录
     */
    @Override
    public List<FeApartmentCancel> selectFeApartmentCancelList(FeApartmentCancel feApartmentCancel) {
        return feApartmentCancelMapper.selectFeApartmentCancelList(feApartmentCancel);
    }

    /**
     * 新增公寓退租记录
     *
     * @param feApartmentCancel 公寓退租记录
     * @return 结果
     */
    @Transactional
    @Override
    public int insertFeApartmentCancel(FeApartmentCancel feApartmentCancel) {
        feApartmentCancel.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
        //feApartmentCancel.setApproval(SecurityUtils.getUsername());
        feApartmentCancel.setCreateTime(DateUtils.getNowDate());
        feApartmentCancel.setCreateBy(SecurityUtils.getUsername());
        //todo 按照面积退租 ， refundArea；
        int rows = feApartmentCancelMapper.insertFeApartmentCancel(feApartmentCancel);
        insertFeApartmentCancelDetail(feApartmentCancel);
        // 生成退租账单,
        FeApartmentCancelBill apartmentCancelFee = new FeApartmentCancelBill();
        apartmentCancelFee.setCancelId(feApartmentCancel.getId());
        apartmentCancelFee.setBillMoney(feApartmentCancel.getTotal());
        apartmentCancelFeeService.insertFeApartmentCancelBill(apartmentCancelFee );
        return rows;
    }

    /**
     * 修改公寓退租记录
     *
     * @param feApartmentCancel 公寓退租记录
     * @return 结果
     */
    @Transactional
    @Override
    public int updateFeApartmentCancel(FeApartmentCancel feApartmentCancel) {
        feApartmentCancel.setUpdateTime(DateUtils.getNowDate());
        feApartmentCancel.setUpdateBy(SecurityUtils.getUsername());
        feApartmentCancelMapper.deleteFeApartmentCancelDetailByCancelId(feApartmentCancel.getId());
        insertFeApartmentCancelDetail(feApartmentCancel);
        return feApartmentCancelMapper.updateFeApartmentCancel(feApartmentCancel);
    }

    /**
     * 批量删除公寓退租记录
     *
     * @param ids 需要删除的公寓退租记录ID
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteFeApartmentCancelByIds(String[] ids) {
        feApartmentCancelMapper.deleteFeApartmentCancelDetailByCancelIds(ids);
        return feApartmentCancelMapper.deleteFeApartmentCancelByIds(ids);
    }

    /**
     * 删除公寓退租记录信息
     *
     * @param id 公寓退租记录ID
     * @return 结果
     */
    @Override
    public int deleteFeApartmentCancelById(String id) {
        feApartmentCancelMapper.deleteFeApartmentCancelDetailByCancelId(id);
        return feApartmentCancelMapper.deleteFeApartmentCancelById(id);
    }

    @Override
    public FeApartmentCancel selectFeApartmentCancelVOById(String id) {
        FeApartmentCancel feApartmentCancel = feApartmentCancelMapper.selectFeApartmentCancelById(id);
        List<FeApartmentCancelDetail> cancelDetails = feApartmentCancel.getFeApartmentCancelDetailList();
        if(cancelDetails.isEmpty())
            return null;
        //分组 ，查询合同信息，hashMap,key,合同id
        Map<String,List<FeApartmentCancelDetail>> cancelMap = cancelDetails.stream().filter(item->StringUtils.isNotBlank(item.getLeaseId())).collect(Collectors.groupingBy(FeApartmentCancelDetail::getLeaseId));
        List<FeApartmentCancelDetailGroup> groups = new ArrayList<>();
        //
        for(Map.Entry entry:cancelMap.entrySet()){
            if(StringUtils.isNotBlank(entry.getKey().toString())){
                FeApartment feApartment = feApartmentMapper.selectFeApartmentById(entry.getKey().toString());
                FeApartmentCancelDetailGroup cancelGroup = new FeApartmentCancelDetailGroup();
                cancelGroup.setContractArea(feApartment.getContractArea());
                cancelGroup.setFeApartmentCancelDetailList((List<FeApartmentCancelDetail>)entry.getValue());
                cancelGroup.setLeaseModel(feApartment.getLeaseModel());
                if(cancelGroup.getLeaseModel().equals("按面积")){
                    cancelGroup.setRefundArea(cancelGroup.getFeApartmentCancelDetailList().get(0).getRefundArea());
                }
                cancelGroup.setLeaseNum(feApartment.getLeaseNum());
                groups.add(cancelGroup);
            }

        }
        feApartmentCancel.setFeApartmentCancelDetailGroupList(groups);
        feApartmentCancel.setFeApartmentCancelDetailList(null);
        return feApartmentCancel;
    }


    @Autowired
    private IFeApartmentLeaseDetailService leaseDetailService;

    @Override
    public List<FeApartmentCancelDetailGroup> selectLeaseDetailGroupVOById(String enteripseId) {
        List<FeApartmentCancelDetailGroup> groups = new ArrayList<>();
        //enteripseid 查询 合同列表
        FeApartment feApartment = new FeApartment();
        feApartment.setEnterpriseId(enteripseId);
        List<FeApartment> feApartmentList = feApartmentMapper.selectFeApartmentList(feApartment);
        if(!feApartmentList.isEmpty()){
            for(FeApartment fe:feApartmentList){
                FeApartmentCancelDetailGroup group = new FeApartmentCancelDetailGroup();
                group.setLeaseNum(fe.getLeaseNum());
                group.setLeaseModel(fe.getLeaseModel());
                group.setContractArea(fe.getContractArea());
                FeApartmentLeaseDetail detail = new FeApartmentLeaseDetail();
                detail.setLeaseId(fe.getId());
                detail.setState(1L);
                List<FeApartmentLeaseDetail> leaseDetails = leaseDetailService.selectFeApartmentLeaseDetailList(detail);
                List<FeApartmentCancelDetail> feApartmentCancelDetails = null;
                if(!leaseDetails.isEmpty()){
                    feApartmentCancelDetails = new ArrayList<>(leaseDetails.size());
                    //租金、物业费、保证金从租赁记录中获取
                    for(FeApartmentLeaseDetail feLeD:leaseDetails){
                        FeApartmentCancelDetail e = new FeApartmentCancelDetail();
                        e.setLeaseDetailId(feLeD.getId());
                        //保证金
                        e.setMargin(feLeD.getMargin());
                        e.setRoomCode(feLeD.getRoomCode());
                        e.setRoomId(feLeD.getRoomId());
                        e.setLeaseId(feLeD.getLeaseId());
                        //物业费
                        e.setProperty(feLeD.getFeProperty());
                        //租金
                        e.setRental(feLeD.getRent());
                        feApartmentCancelDetails.add(e);
                    }

                }else {
                    continue;
                }
                group.setFeApartmentCancelDetailList(feApartmentCancelDetails);
                groups.add(group);
            }
        }

        return groups;
    }

    /**
     * 新增公寓退租详情信息
     *
     * @param feApartmentCancel 公寓退租记录对象
     */
    public void insertFeApartmentCancelDetail(FeApartmentCancel feApartmentCancel) {
        List<FeApartmentCancelDetail> feApartmentCancelDetailList = new ArrayList<>();
        List<FeApartmentCancelDetailGroup> feApartmentCancelDetailGroupList = feApartmentCancel.getFeApartmentCancelDetailGroupList();
        if(StringUtils.isNotNull(feApartmentCancelDetailGroupList)){
            for(FeApartmentCancelDetailGroup group:feApartmentCancelDetailGroupList){

                if(group.getLeaseModel().equals("按面积")){
                    FeApartment feApartment = new FeApartment();
                    feApartment.setLeaseNum(group.getLeaseNum());
                    List<FeApartment> list = feApartmentMapper.selectFeApartmentList(feApartment);
                    feApartment = list.get(0);
                    //更新租赁合同面积
                    if(group.getRefundArea() != null){
                        feApartment.setContractArea(feApartment.getContractArea().subtract(group.getRefundArea()));
                        group.getFeApartmentCancelDetailList().stream().forEach(item->{
                            item.setRefundArea(group.getRefundArea());
                        });
                    }else {
                        log.error("insertFeApartmentCancelDetail; " +"退租面积不能为空");
                    }

                    if(feApartment.getContractArea().compareTo(BigDecimal.ZERO) <= 0){
                        feApartment.setContractArea(BigDecimal.ZERO);
                        feApartment.setRecordState("已到期");
                    }
                    feApartmentMapper.updateFeApartment(feApartment);

                }

                feApartmentCancelDetailList.addAll(group.getFeApartmentCancelDetailList());

            }
        }
        //按房间退租
        String id = feApartmentCancel.getId();
        if (StringUtils.isNotEmpty(feApartmentCancelDetailList)) {
            List<FeApartmentCancelDetail> list = new ArrayList<FeApartmentCancelDetail>();
            for (FeApartmentCancelDetail feApartmentCancelDetail : feApartmentCancelDetailList){
                feApartmentCancelDetail.setCancelId(id);
                feApartmentCancelDetail.setId(IdUtil.getSnowflake(0, 0).nextIdStr());
                list.add(feApartmentCancelDetail);
            }
            if (list.size() > 0) {
                feApartmentCancelMapper.batchFeApartmentCancelDetail(list);
                //批量更新房间，房屋租赁记录状态，room状态
                FeApartmentLeaseDetail detail1 = new FeApartmentLeaseDetail();
                BuiRoom buiRoom = new BuiRoom();
                for(FeApartmentCancelDetail detail:list){
                    detail1.setId(detail.getLeaseDetailId());
                    detail1.setState(0L);
                    feApartmentLeaseDetailMapper.updateFeApartmentLeaseDetail(detail1);
                    // 查询租赁合同是否已经退租所有房间，退租完成，更新租赁状态已到期
                    detail1 = feApartmentLeaseDetailMapper.selectFeApartmentLeaseDetailById(detail.getLeaseDetailId());
                    FeApartmentLeaseDetail temp = new FeApartmentLeaseDetail();
                    temp.setLeaseId(detail1.getLeaseId());
                    temp.setState(1L);
                    List<FeApartmentLeaseDetail> detailList = feApartmentLeaseDetailMapper.selectFeApartmentLeaseDetailList(temp);
                    if(StringUtils.isEmpty(detailList)){
                        FeApartment feApartment = new FeApartment();
                        feApartment.setId(detail1.getLeaseId());
                        feApartment.setRecordState("已到期");
                        feApartmentMapper.updateFeApartment(feApartment);
                    }
                    buiRoom.setId(detail.getRoomId());
                    buiRoom.setLeaseState(LeaseStateEnum.待租.getCode());
                    buiRoom.setRecordId("");
                    buiRoomManager.updateRoom(buiRoom);

                }
            }

        }

    }
}
